/*
 * Copyright 2012 alex.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mkdir.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.lang3.Validate;
import org.mkdir.model.Dokumentum;
import org.mkdir.util.jsf.MessageBundle;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author alex
 */
public final class DokumentumokUtil {

    private DokumentumokUtil() {
    }

    public static StreamedContent getLetoltendoDokumentum(Dokumentum[] dokumentumok) {
        Validate.notEmpty(dokumentumok);
        InputStream inputStream;
        String fajlnev;
        if (dokumentumok.length > 1) {
            inputStream = new ByteArrayInputStream(getZippeltDokumentumok((Dokumentum[]) dokumentumok));
            fajlnev = MessageBundle.getMessage(Konstans.LETOLTOTT_DOK_FAJLNEV_PREFIX) + new Date().getTime() + Konstans.ZIP_POSTFIX;
        } else {
            inputStream = new ByteArrayInputStream(dokumentumok[0].getDokumentum());
            fajlnev = dokumentumok[0].getNev();
        }

        return new DefaultStreamedContent(inputStream, "", fajlnev);

    }

    private  static byte[] getZippeltDokumentumok(Dokumentum[] dokumentumok) {
        if (dokumentumok != null && dokumentumok.length > 0) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ZipOutputStream zos = new ZipOutputStream(baos);
                for (Dokumentum dok : dokumentumok) {
                    ZipEntry entry = new ZipEntry(dok.getNev());
                    zos.putNextEntry(entry);
                    zos.write(dok.getDokumentum());
                    zos.closeEntry();
                }
                zos.close();
                return baos.toByteArray();
            } catch (IOException ex) {
                Logger.getLogger(FajlUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
}
